<template>
  <div class="goods-management">
    <div class="card goods-management__header">
      <el-form inline>
        <el-form-item label="物品类型">
          <el-cascader
            v-model="params.goodsType"
            :options="goodsTypeOptions"
            :props="{ value: 'id', label: 'name' }"
            clearable
          />
        </el-form-item>
        <!--        <el-form-item label="是否有库存">-->
        <!--          <el-select-->
        <!--            v-model="params.isHaveStock"-->
        <!--            placeholder="请选择"-->
        <!--            clearable-->
        <!--          >-->
        <!--            <el-option-->
        <!--              v-for="item in selectOptions"-->
        <!--              :key="item.value"-->
        <!--              :label="item.label"-->
        <!--              :value="item.value"-->
        <!--            />-->
        <!--          </el-select>-->
        <!--        </el-form-item>-->

        <el-form-item>
          <el-button
            size="medium"
            type="danger"
            @click="handleReset"
          >重置</el-button>

          <el-button
            size="medium"
            type="primary"
            @click="handleSearch"
          >查询</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="card goods-management__content">
      <el-table
        v-loading="loading"
        :data="list"
        border
        stripe
      >
        <el-table-column
          label="物品名称"
          prop="goods.name"
          align="center"
        />
        <el-table-column
          label="物品类型"
          prop="goods.goods_type.name"
          align="center"
        />

        <el-table-column
          label="库存数"
          prop="quantity"
          align="center"
        >
          <template v-slot="{ row }">
            {{ row.quantity }}
            {{ row?.goods.unit }}
          </template>
        </el-table-column>

        <el-table-column
          label="主计量单位"
          prop="goods.unit"
          align="center"
        />

        <el-table-column
          label="辅助计量单位数量"
          prop="quantity"
          align="center"
        >
          <template v-slot="{ row }">
            <el-button
              v-if="row.goods.goods_type_unit.length > 0"
              type="text"
              @click="handleOpenDialog(row)"
            >查看</el-button>

            <span v-else>-</span>
          </template>
        </el-table-column>

        <el-table-column
          label="是否有库存"
          prop="quantity"
          align="center"
        >
          <template v-slot="{ row }">
            <el-tag v-if="row.quantity > 0" type="primary">有库存</el-tag>
            <el-tag v-else type="danger">无库存</el-tag>
          </template>
        </el-table-column>

        <el-table-column
          label="操作"
          align="center"
        >
          <template v-slot="{ row }">
            <el-dropdown @command="handleCommand($event, row)">
              <el-button type="text">库存调整</el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="store">
                    <div style="text-align: center;">
                      入库
                    </div>
                  </el-dropdown-item>
                  <el-dropdown-item command="outbound">
                    <div style="text-align: center;">
                      出库
                    </div>
                  </el-dropdown-item>
                  <el-dropdown-item command="hand">
                    <div style="text-align: center;">
                      手动调整
                    </div>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>

            <el-button
              type="text"
              style="margin-left: 10px;"
              @click="handleViewDetails(row)"
            >
              详情查看
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="goods-management__content__pagination">
        <Pagination
          style="margin-top: 0; padding: 0;"
          :total="total"
          :limit="params.paginate"
          @pagination="pagination"
        />
      </div>
    </div>

    <AuxiliaryUnitWithQuantityDialog
      :visible.sync="unitDialogVisible"
      :quantity-info="quantityInfo"
      :quantity="currentGoodsQuantity"
      :main-unit="currentMainUnit"
    />

    <WarehouseWarrantDialog
      ref="inboundRef"
      :visible.sync="showInboundDialog"
      :model="formModel"
      :goods-units="unitList"
      :loading="btnLoading"
      @confirm="handleInboundConfirm"
    />

    <CreateStockOutDialog
      ref="outboundRef"
      :visible.sync="showOutboundDialog"
      :model="formModel"
      :loading="btnLoading"
      :unit-list="unitList"
      :quantity="currentGoodsQuantity"
      @confirm="handleOutboundConfirm"
    />

    <CreateInventoryAdjustDialog
      ref="stockAdjustRef"
      :visible.sync="showStockAdjustDialog"
      :model="formModel"
      :loading="btnLoading"
      :unit-list="unitList"
      :quantity="currentGoodsQuantity"
      @confirm="handleStockAdjustConfirm"
    />

  </div>
</template>
<script>
import { getGoodsList, getGoodsType, createInAndOutRecord } from '@/api/officeSuppliesManagement'
import Pagination from '@/components/Pagination/index.vue'
import dayjs from 'dayjs'
import { sleep } from '@/utils'
import AuxiliaryUnitWithQuantityDialog
from '@/views/officeSuppliesManagement/components/AuxiliaryUnitWithQuantityDialog.vue'
import WarehouseWarrantDialog from '@/views/officeSuppliesManagement/components/WarehouseWarrantDialog.vue'
import CreateStockOutDialog from '@/views/officeSuppliesManagement/components/stockOut/CreateStockOutDialog.vue'
import CreateInventoryAdjustDialog
from '@/views/officeSuppliesManagement/components/goodsInventory/CreateInventoryAdjustDialog.vue'

export default {
  name: '',
  components: {
    AuxiliaryUnitWithQuantityDialog,
    Pagination,
    WarehouseWarrantDialog,
    CreateStockOutDialog,
    CreateInventoryAdjustDialog
  },
  data() {
    return {
      list: [],
      params: {
        page: 1,
        paginate: 10,
        goodsType: null
      },
      total: 0,
      loading: false,
      goodsTypeOptions: [],
      unitDialogVisible: false,
      quantityInfo: null,
      currentGoodsQuantity: null,
      currentMainUnit: null,
      showInboundDialog: false,
      showOutboundDialog: false,
      showStockAdjustDialog: false,
      formModel: {
        goods_id: null,
        unit_id: null,
        adjust_quantity: 1,
        reason: '',
        operate_type: '',
        adjust_time: '',
        adjust_user_id: ''
      },
      btnLoading: false,
      unitList: []
    }
  },
  created() {
    this.getGoodsList()
    this.getGoodsType()
  },
  methods: {

    async getGoodsList() {
      this.loading = true
      try {
        const res = await getGoodsList(this.generateParams(this.params))
        this.list = res.data.data
        this.total = res.data.total
      } catch (error) {
        this.$message.error(error?.message || '库存信息获取失败')
      } finally {
        await sleep()
        this.loading = false
      }
    },

    generateParams() {
      const len = this.params.goodsType?.length
      return {
        ...this.params,
        goodsType: len > 0 ? this.params.goodsType[len - 1] : null
      }
    },

    async getGoodsType() {
      try {
        const res = await getGoodsType()
        this.goodsTypeOptions = res.data
      } catch (error) {
        throw new Error(error?.response?.data?.message || '信息获取失败')
      }
    },

    pagination(page) {
      this.params.page = page.page
      this.params.paginate = page.limit
      this.getGoodsList()
    },

    timeFormat(t) {
      return dayjs(t).format('YYYY-MM-DD HH:mm:ss')
    },

    handleSearch() {
      this.params.page = 1
      this.getGoodsList()
    },

    handleReset() {
      this.params = this.$options.data().params
      this.getGoodsList()
    },

    handleOpenDialog(row) {
      console.log('row --------->', row)
      this.quantityInfo = row.goods.goods_type_unit
      this.currentGoodsQuantity = row.quantity
      this.currentMainUnit = row.goods.unit
      this.unitDialogVisible = true
    },

    handleCommand(e, row) {
      console.log('row --------->', row)
      console.log('e --------->', e)
      this.formModel = this.$options.data().formModel
      this.unitList = row.goods.goods_type_all_unit
      this.currentGoodsQuantity = row.quantity
      switch (e) {
        case 'store':
          this.handleOpenInboundDialog(row)
          break

        case 'outbound':
          this.handleOpenOutboundDialog(row)
          break

        case 'hand':
          this.handleOpenStockAdjustDialog(row)
          break
      }
    },

    handleOpenStockAdjustDialog(row) {
      this.formModel.goods_id = row.goods_id
      this.formModel.operate_type = 'hand'

      this.showStockAdjustDialog = true

      this.$nextTick(() => {
        this.$refs.stockAdjustRef.resetFields()
      })
    },

    async handleStockAdjustConfirm(e) {
      await this.adjustInStockFetcher(this.formModel)
      this.showStockAdjustDialog = false
    },

    handleOpenOutboundDialog(row) {
      this.formModel.goods_id = row.goods_id
      this.formModel.operate_type = 'outbound'
      this.showOutboundDialog = true
      this.$nextTick(() => {
        this.$refs.outboundRef.resetFields()
      })
    },

    async handleOutboundConfirm(e) {
      await this.adjustInStockFetcher({
        ...this.formModel,
        adjust_quantity: this.formModel.adjust_quantity * -1
      })
      this.showOutboundDialog = false
    },

    handleOpenInboundDialog(row) {
      this.formModel.goods_id = row.goods_id
      this.formModel.operate_type = 'store'
      this.showInboundDialog = true
      this.$nextTick(() => {
        this.$refs.inboundRef.resetFields()
      })
    },

    async handleInboundConfirm() {
      console.log('this.formModel --------->', this.formModel)
      await this.adjustInStockFetcher(this.formModel)
      this.showInboundDialog = false
    },

    async adjustInStockFetcher(data) {
      this.btnLoading = true
      try {
        const res = await createInAndOutRecord(data)
        console.log('res --------->', res)
        this.$message.success('操作成功')
        this.refresh()
      } catch (error) {
        this.$message.error(error?.message || '操作失败')
      } finally {
        this.btnLoading = false
      }
    },

    refresh() {
      this.params = this.$options.data().params
      this.getGoodsList()
    },

    handleViewDetails(row) {
      console.log('row --------->', row)
      this.$store.dispatch('officeManagement/changeCurrentGoods', row)
      this.$router.push({
        name: 'goodsDetails',
        query: {
          id: row.id
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.goods-management {
  padding: 20px;

  &__header {
    ::v-deep(.el-form-item) {
      margin-bottom: 0;
      margin-right: 20px;
    }
  }

  &__content {

    &__pagination {
      margin-top: 20px;
      display: flex;
      justify-content: end;
    }
  }

  .card {
    padding: 20px;
    background-color: #fff;
    border-radius: 4px;
    margin-bottom: 20px;
  }
}
</style>
